from __future__ import absolute_import
import ast
import logging

from rest_framework import serializers

from .models import EventData, AlarmData

logger = logging.getLogger(__name__)


class EventTraceDataSerializer(serializers.ModelSerializer):

    detail = serializers.SerializerMethodField()

    class Meta:

        model = EventData
        fields = "__all__"
        extra_kwargs = {
            "details": {"write_only": True}
        }

    def get_detail(self, obj):
        if isinstance(obj.details, str) and obj.details != '--':
            try:
                detail = ast.literal_eval(obj.details)
            except Exception as e:
                detail = obj.details
                logger.info("the event %s ast failed: %s", obj.event_name, e)
            return detail
        return obj.details


class AlarmTraceDataSerializer(serializers.ModelSerializer):

    detail = serializers.SerializerMethodField()

    class Meta:

        model = AlarmData
        fields = "__all__"
        extra_kwargs = {
            "details": {"write_only": True},
        }

    def get_detail(self, obj):
        if isinstance(obj.details, str) and obj.details != '--':
            try:
                detail = ast.literal_eval(obj.details)
            except Exception as e:
                detail = obj.details
                logger.info("the alarm %s ast failed: %s", obj.alarm_name, e)
            return detail
        return obj.details
